<template>
  <el-dialog
    title="分享设置"
    :visible.sync="visible"
    width="788px"
    top="10vh"
    :close-on-click-modal="false"
    class="dialog-container"
    @close="handlerClose"
  >
    <el-form ref="shareForm" :model="formData" :rules="rules" size="small" label-width="92px">
      <el-form-item label="分享试卷">
        {{ paper.title }}
      </el-form-item>
      <el-form-item label="考试时间" prop="time">
        <el-date-picker
          v-model="timestamp"
          value-format="timestamp"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
        <div class="edu-tips">为空表示随时可以作答</div>
      </el-form-item>
      <el-form-item label="作答次数" prop="exam_number">
        <el-input-number v-model="formData.exam_number" :min="0" :step="1" />
        <div class="edu-tips">0 表示不限制作答次数</div>
      </el-form-item>
      <el-form-item label="人脸验证" prop="face_verification">
        <el-switch v-model="formData.face_verification" :active-value="1" :inactive-value="0"></el-switch>
        <div class="edu-tips">开启后，进入考试需要进行人脸验证</div>
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input v-model="formData.code" class="code" maxlength="6" show-word-limit></el-input>
        <div class="edu-tips">设置6位验证码，验证码为空则不需要验证码即可参加考试</div>
      </el-form-item>
      <el-form-item label="白名单" prop="face_verification">
        <!--remote-->
        <!--:remote-method="searchUser"-->
        <!-- reserve-keyword-->
        <el-select
          v-model="userPhone"
          filterable
          remote
          :remote-method="searchUser"
          placeholder="请输入学员昵称或手机号搜索"
          no-match-text="无匹配学员"
          :loading="searchUserLoading"
          @change="addUser"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.value"
            :label="item.title"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <div class="edu-tips">仅在白名单的学员可参加考试，白名单为空则所有学员都可以参考考试</div>
        <div class="white-user-list">
          <el-tag
            v-for="user in userList"
            :key="user.value"
            closable
            :disable-transitions="false"
            @close="removeUser(user.value)"
          >
            {{ user.title }}
          </el-tag>
        </div>
      </el-form-item>
      <el-form-item label="链接地址">
        <el-row type="flex">
          <el-link :underline="false" type="primary">
            <!--<el-tooltip-->
            <!--  content="点击复制"-->
            <!--  placement="top"-->
            <!--  effect="light"-->
            <!--  transition="el-collapse-transition"-->
            <!--  :hide-after="3000"-->
            <!--&gt;-->
            <!--  <span-->
            <!--    v-clipboard:copy="examUrl"-->
            <!--    v-clipboard:success="copySuccess"-->
            <!--  >{{ examUrl }}</span>-->
            <!--</el-tooltip>-->
            <span
              v-clipboard:copy="examUrl"
              v-clipboard:success="copySuccess"
              class="exam-url"
            >{{ examUrl }}</span>
          </el-link>
          <el-button
            v-clipboard:copy="examUrl"
            v-clipboard:success="copySuccess"
            type="primary"
            size="mini"
          >
            复制
          </el-button>
        </el-row>
      </el-form-item>
      <el-form-item label="二维码">
        <vue-qr
          :text="examUrl"
          :correct-level="3"
          :dot-scale="0.7"
          :auto-color="false"
          :margin="0"
          :size="164"
          class="qrcode"
        />
        <!--:logo-margin="3"-->
        <!--:logo-scale="0.21"-->
      </el-form-item>
      <form-footer
        :loading="confirmLoading"
        confirm-btn-text="保存"
        :cancel-btn="false"
        @cancel="handlerClose"
        @submit="handlerConfirm"
      />
    </el-form>
  </el-dialog>
</template>

<script>
import VueQr from 'vue-qr'
import HttpBuildQuery from 'http-build-query'
import SparkMD5 from 'spark-md5'
import FormFooter from '@/components/form-footer'

// import encode from 'encode-3986'

import { mapGetters } from 'vuex';

export default {
  name: 'ShareConfigDialog',
  components: {
    VueQr,
    FormFooter
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    paper: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      confirmLoading: false,
      formData: {
        exam_number: 0,
        face_verification: 0
      },
      timestamp: null,
      rules: {},
      userPhone: '', // 搜索关键字
      userOptions: [], // 学员选项
      userList: [], // 选中的学员
      searchUserLoading: false
    }
  },
  computed: {
    ...mapGetters('website', ['effectiveDomain']),
    examUrl() {
      const params = this.examParams
      const sign = this.$http.signature(params)

      // 签名参数
      params.sg_t = sign['E-APP-TIMESTAMP']
      params.sg_n = sign['E-APP-NONCE']
      params.sg_s = sign['E-APP-SIGN']

      return this.effectiveDomain + '/exam/share?' + HttpBuildQuery(params)
    },
    examParams() {
      // 用户列表
      if (Array.isArray(this.userList) && this.userList.length > 0) {
        this.$set(this.formData, 'user', this.userList.map(item => item.value))
      } else {
        this.$delete(this.formData, 'user')
      }

      // 验证码
      if (this.formData.code === '') {
        this.$delete(this.formData, 'code')
      }

      // 人脸验证
      if (this.formData.face_verification === 0) {
        this.$delete(this.formData, 'face_verification')
      }

      const keys = Object.keys(this.formData)
      const params = {}
      const map = {
        exam_number: 'n',
        face_verification: 'f',
        user: 'u',
        code: 'c',
        start_time: 'st',
        end_time: 'et'
      }
      keys.forEach(k => {
        let val
        if (k === 'code') {
          val = SparkMD5.hash(this.formData.code)
        } else if (k === 'user') {
          val = this.formData.user.join()
        } else {
          val = this.formData[k]
        }
        params[map[k]] = val
      })
      params.id = this.paper.id

      return params
    }
  },
  watch: {
    timestamp(date) {
      if (Array.isArray(date)) {
        this.$set(this.formData, 'start_time', date[0])
        this.$set(this.formData, 'end_time', date[1])
      } else {
        this.$delete(this.formData, 'start_time')
        this.$delete(this.formData, 'end_time')
      }
    }
  },
  created() {
    this.loadConfigdata()
  },
  methods: {
    loadConfigdata() {
      this.$http.get(
          '/exam/admin/paper/share/settings',
          {
            paper_id: this.paper.id
          },
          ({ data }) => {
            const {
              start_time: startTime,
              end_time: endTime,
              user_list: userList = []
            } = data

            this.timestamp = [startTime, endTime]

            this.$delete(data, 'user_list')

            this.formData = {
              ...this.formData,
              ...data
            }

            this.userList = userList
          },
          ({ msg }) => {
            this.$message.error(msg)
            this.confirmLoading = false
          },
          false
      )
    },
    // 关闭后重置字段
    handlerClose() {
      this.$emit('update:visible', false);
    },
    // 保存配置
    handlerConfirm() {
      this.confirmLoading = true
      this.$http.post(
          '/exam/admin/paper/share/settings',
          {
            ...this.formData,
            paper_id: this.paper.id
          },
          ({ msg }) => {
            this.$message.success(msg)
            this.confirmLoading = false
          },
          ({ msg }) => {
            this.$message.error(msg)
            this.confirmLoading = false
          },
          false
      )
    },
    copySuccess() {
      this.$message.success('复制成功')
    },
    // 移除用户
    removeUser(userId) {
      const index = this.userList.findIndex(item => item.value === userId)

      this.userList.splice(index, 1)
    },
    // 添加用户
    addUser(value) {
      const user = this.userOptions.find(user => user.value === value)
      if (user) {
        if (this.userList.findIndex(user => user.value === value) !== -1) {
          this.$message.warning('学员已在白名单中')
        } else {
          this.userList.push(user)
        }
      }
    },
    // 搜索学员
    searchUser(keyword) {
      if (keyword !== '') {
        this.searchUserLoading = true
        this.$http.get(
            '/user/admin/account/search',
            {
              keyword
            },
            ({ data }) => {
              this.userOptions = data
              this.searchUserLoading = false
            },
            ({ msg }) => {
              this.$message.error(msg)
              this.searchUserLoading = false
            },
            false
        )
      } else {
        this.searchUserLoading = false
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import "@/styles/mixin.scss";

.dialog-container {
  .type-list {
    .type-list-item {
      margin-bottom: 10px;

      &:last-child {
        margin-bottom: 0;
      }

      .el-select {
        width: 100%;
      }
    }
  }

  .white-user-list {
    .el-tag {
      margin-right: 8px;
      margin-bottom: 8px;
    }
  }

  .code.el-input {
    width: 215px;
  }

  .exam-url {
    @include ellipsisLine(1);
  }
}
</style>
